package com.jeesuite.bestpl.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.eventbus.AsyncEventBus;
import com.jeesuite.bestpl.api.IPostService;
import com.jeesuite.bestpl.dto.Comment;
import com.jeesuite.bestpl.dto.IdNamePair;
import com.jeesuite.bestpl.dto.Message;
import com.jeesuite.bestpl.dto.Page;
import com.jeesuite.bestpl.dto.PageQueryParam;
import com.jeesuite.bestpl.dto.Post;
import com.jeesuite.bestpl.security.LoginUserInfo;
import com.jeesuite.bestpl.security.SecurityUtil;

@RestController
@RequestMapping("/post")
public class PostController {

	@Autowired
	private IPostService service;
	
	@Autowired
	private AsyncEventBus asyncEventBus;
	
	@RequestMapping(value = "categorys", method = RequestMethod.GET)
	public List<IdNamePair> findAllPostCategory(){
		return service.findAllPostCategory();
	}
	
	public boolean addPost(Post post){
		service.addPosts(post);
		return true;
	}
	
	
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Post getById(@PathVariable("id") int id){
		return service.findPostById(id);
	}
	
	@RequestMapping(value = "{sortType}/{topLimit}", method = RequestMethod.GET)
	public List<Post> findTopPost(@RequestParam(value="categoryId",required = false) int categoryId,@PathVariable("sortType") String sortType,@PathVariable("topLimit") int topLimit){
		return service.findTopPost(categoryId, sortType, topLimit);
	}
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public Page<Post> pageQueryPost(final PageQueryParam param){
		return service.pageQueryPost(param);
	}
	
	@RequestMapping(value = "add_comment", method = RequestMethod.POST)
	public Boolean addPostComment(Comment comment){
		
		Post post = service.findPostById(comment.getPostId());
		
		LoginUserInfo userInfo = SecurityUtil.getLoginUserInfo();
		comment.setUserId(userInfo.getId());
		comment.setUserName(userInfo.getName());
		service.addPostComment(comment);
		//通知帖子作者评论内容
		Message message = new Message();
		message.setFromUid(userInfo.getId());
		message.setFromUname(userInfo.getName());
		message.setToUid(post.getUserId());
		message.setToUname(post.getUserName());
		message.setContent(comment.getContent());
		
		asyncEventBus.post(message);
		
		return true;
	}
	
	@RequestMapping(value = "comment/list", method = RequestMethod.POST)
	public Page<Comment> pageQueryPostComment(@RequestParam("postId") int postId,@RequestParam("pageNo") int pageNo,@RequestParam("pageSize") int pageSize){
		return service.pageQueryPostComment(postId, pageNo, pageSize);
	}
}
